package service

import (
	"errors"
	"fmt"
	"github.com/gccai/write_helper/config"
	"github.com/gccai/write_helper/model"
	"github.com/gccai/write_helper/query"
	"github.com/gccai/write_helper/repository"
	"github.com/gccai/write_helper/utils"
	uuid "github.com/hashicorp/go-uuid"
)

type UserSrv interface {
	// 查看所有的用户
	List(req *query.ListQuery) (users []*model.User, err error)
	// 获取用户总数
	GetTotal(req *query.ListQuery) (total int, err error)
	// 获取某个用户的信息
	Get(user model.User) (*model.User, error)
	// 查寻用户、查找某个用户
	Exist(user model.User) *model.User
	// 按照 id 查找用户
	ExistByUserID(id string) *model.User
	// 按照手机号查找用户
	ExistbyMobile(mobile string) *model.User
	// 添加用户
	Add(user model.User) (*model.User, error)
	// 更新
	Edit(user model.User) (bool, error)
	// 删除
	Delete(id string) (bool, error)
}

type UserService struct {
	Repo repository.UserRepositoryInterface
}

// 在服务层，对limit进行限制，超过10的就是那个数，如果没有超过10,那就定到10
func (u UserService) List(req *query.ListQuery) (users []*model.User, err error) {
	if req.PageSize < 10 {
		req.PageSize = config.PAGE_SIZE
	}
	return u.Repo.List(req)
}

// 这个查寻因为是返回一个数，不需要分页操作
func (u UserService) GetTotal(req *query.ListQuery) (total int, err error) {
	return u.Repo.GetTotal(req)
}

func (u UserService) Get(user model.User) (*model.User, error) {
	return u.Repo.Get(user)
}

func (u UserService) Exist(user model.User) *model.User {
	return u.Repo.Exist(user)
}

func (u UserService) ExistByUserID(id string) *model.User {
	return u.Repo.ExistByUserID(id)
}

func (u UserService) ExistbyMobile(mobile string) *model.User {
	return u.Repo.ExistbyMobile(mobile)
}

func (u UserService) Add(user model.User) (*model.User, error) {
	result := u.Repo.ExistbyMobile(user.Mobile)
	if result != nil {
		return nil, errors.New("用户已经存在")
	}
	//TODO 这快不应该这样，需要写日志，然后用定时器，不能不停的循环下去。
GenerateUUID:
	UUID, err := uuid.GenerateUUID()
	if err != nil {
		fmt.Println("uuid 生成 错误，重新生成中")
		goto GenerateUUID
	}
	user.UserId = UUID
	if user.Password == "" {
		user.Password = utils.Md5("123456")
	}else{
		user.Password = utils.Md5(user.Password)
	}
	user.IsDeleted = false
	user.IsLocked = false
	return u.Repo.Add(user)
}

// 只能更改 名称，电话，地址
func (u UserService) Edit(user model.User) (bool, error) {
	fmt.Print(user.UserId)
	if user.UserId == "" {
		return false, fmt.Errorf("参数错误:userid为空")
	}
	exist := u.Repo.Exist(user)
	if exist == nil {
		return false, errors.New("参数错误：用户不存在")
	}
	// exist.UserId = user.UserId
	exist.NickName = user.NickName
	exist.Mobile = user.Mobile
	exist.Address = user.Address
	return u.Repo.Edit(*exist)
}

func (u UserService) Delete(id string) (bool, error) {
	if id == "" {
		return false, errors.New("参数错误:id == nil")
	}
	user := u.ExistByUserID(id)
	//fmt.Println(user)
	if user == nil {
		return false, errors.New("参数错误: user is not exist")
	}
	//fmt.Println(*user)
	user.IsDeleted = !user.IsDeleted
	//fmt.Println(*user)
	return u.Repo.Delete(*user)
}
